import React from 'react';
import { Route, Redirect, RouteProps } from 'react-router';
import { hasToken } from '@/utils/storage';
import history from '@/utils/history';

// 继承RouteProps
export interface Props extends RouteProps {
  path: string;
  component: React.FC;
}

export type LocationStateType = {
  from: string;
};
export default function AuthRoute(props: Props) {
  const { path, component: Component, ...restProps } = props;
  return (
    <Route
      {...restProps}
      path={path}
      render={() => {
        if (hasToken()) {
          //   有token就渲染组件
          return <Component />;
        } else {
          //   没有token重定向到登陆页面
          return (
            <Redirect
              to={{
                pathname: '/login',
                // 通过state存储重定向前的页面路径,用于登录成功后回调
                state: { from: history.location.pathname } as LocationStateType,
              }}
            ></Redirect>
          );
        }
      }}
    ></Route>
  );
}
